package com.qf.cloud2204.microToken.controller;

import cn.hutool.jwt.JWT;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;


@RestController
@RequestMapping("/token")
public class TokenController {


@HystrixCommand(fallbackMethod = "genTokenFallback")
    //颁发token
    @PostMapping("/gentoken")
    public HashMap<String,Object> genToken(String number){
        HashMap<String, Object> map = new HashMap<>();
        //生成一个jwt的key
        String key = "qfsy2204";
        //颁发token
        String token = JWT.create().setKey(key.getBytes())
                .setPayload("number",number)//将手机号存到token payload里
                .setExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60 * 30))
                .sign();
        map.put("code",1);
        map.put("msg","ok");
        map.put("token",token);
        return map;
    }

    public HashMap<String,Object> genTokenFallback(String number){
        HashMap<String, Object> map = new HashMap<>();
        map.put("code",-1);
        map.put("msg","gentoken接口降级了，请重试");
        return map;
    }



    @HystrixCommand(fallbackMethod = "VerifyFallback")
    //校验token
    @PostMapping("/verify")
    public HashMap<String,Object> verify(String token){
        HashMap<String, Object> map = new HashMap<>();
        //生成一个jwt的key
        String key = "qfsy2204";
        if (token==null){
          throw new RuntimeException("没携带token，请携带");
        }
        JWT jwt = JWT.of(token).setKey(key.getBytes());
        boolean validate = jwt.validate(0);
        if (validate){
            map.put("code",1);
            map.put("msg","token ok");
            map.put("number",jwt.getPayload("number"));
            return map;
        }else {
            map.put("code",-1);
            map.put("msg","token error");
            return map;
        }

    }


    public HashMap<String,Object> VerifyFallback(String token){
        HashMap<String, Object> map = new HashMap<>();
        map.put("code",-1);
        map.put("msg","verify接口降级了，请重试");
        return map;
    }
}
